package lli.filemanagement
import grails.converters.XML

class MFileManagerController {
    static String IMG = "img"
    static String DOC = "doc"
    static String OTH = "oth"
    
    // Used to create a new file form ajax way
    def addnewfile = {
        def mfile = new MFile(name: params.name)
        def name = params.fileup.fileItem.name.toLowerCase()
        def size = params.fileup.size
        def file_type = getFileType(params.fileup.fileItem.contentType)

        boolean error = false
        if (file_type.equals(DOC)){
            if (size > 10000000){
                mfile.errors.rejectValue('data', 'file.data.doc.toobig',"Hey ! Are you crazy ? The document can not be greater than 10 Mega !")
            }
        } else if (file_type.equals(IMG)){
            if (size > 10000000){
               mfile.errors.rejectValue('data', 'file.data.image.toobig', "Hey ! Are you crazy ? The document can not be greater than 1 Mega !")
               
            }
        } else if (file_type.equals(OTH)){
            mfile.errors.rejectValue('data', 'file.data.nonauthorized', "Hey ! Are you crazy ? ${params.fileup.fileItem.contentType} is an unauthorized file format ! ")
            
        }
        if (!mfile.hasErrors()){
            mfile.data = new MFileData(data:params.fileup.getBytes())
            mfile.save(flush:true)
        } 
        if (mfile.hasErrors()){
            render mfile.errors.allErrors as XML
        } else {
            render mfile as XML
        }
    }

    def showFile = {
        MFile file = MFile.get(params.id)
        if (!file) {
            println file.errors
        }
        response.outputStream << file.data.data
    }
    
    def getFileType(contentType){
        def fileType
        if (isContentTypePresent(contentType, ['image/gif','image/jpeg' ,'image/png'])){
            fileType = IMG
        } else if (isContentTypePresent(contentType, ['application/pdf', 'application/word'])) {
            fileType = DOC
        } else {
            fileType = OTH
        }
        return fileType
    }

    def isContentTypePresent(String contentType, ArrayList contentTypes){
        def found = false
        contentTypes.find{
            if (it.trim().equals(contentType.trim())){
                found = true
            }
            it.trim().equals(contentType.trim())
        }
        return found
    }
    
    def getfiles = {
        MFile [] files = MFile.list()
        response.outputStream << files[0].data.data
    }
}
